import Sound2DListener from "../../../../core/sound_2d";
import Utils, { Sync } from "../../../../core/utils";
import ReactCamera from "../../../../prefabs/react_camera";
import ReactNode from "../../../../prefabs/react_node";
import World from "../../world";
import Character from "./character";
import CharacterCtrl from "./character_ctrl";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Interface extends cc.Component {
    ctrl: CharacterCtrl = null;
    char: Character = null;
    world: World = null;

    @property(cc.Camera)
    camUI: cc.Camera = null;
    @property(cc.Camera)
    cam: cc.Camera = null;
    @property(ReactCamera)
    camRn: ReactCamera = null;

    minZoom = 0.5;
    maxZoom = 2;
    _zoom = 1;
    get zoom() {
        return this._zoom;
    }
    set zoom(val) {
        let newZoom = val;
        let oldZoom = this.zoom;
        if (oldZoom === newZoom) {
            return;
        }
        this._zoom = Math.max(this.minZoom, Math.min(this.maxZoom, newZoom));
        this.cam.zoomRatio = this._zoom;
        // cc.Tween.stopAllByTarget(this.cam);
        // cc.tween(this.cam).to(Math.abs(oldZoom - newZoom) / 5, { zoomRatio: newZoom }).start();
    }

    sound2DListener: Sound2DListener = null;

    protected onLoad(): void {
        let node = new cc.Node();
        let rn = node.addComponent(ReactNode);
        rn.effectPos = true;
        rn.world = true;
        this.sound2DListener = node.addComponent(Sound2DListener);
        this.node.addChild(node);
    }

    init(char: Character) {
        this.char = char;
        this.ctrl = cc.instantiate(Utils.loader.getAsset<cc.Prefab>("character_ctrl_keyboard", "prefabs", "cc.Prefab")).getComponent(CharacterCtrl);
        this.node.addChild(this.ctrl.node);
        this.ctrl.attach(this.char);

        this.camRn.setTarget(this.char.node);

        //todo:
        Sync.NextUpdate().then(() => {
            this.sound2DListener.getComponent(ReactNode).setTarget(this.char.node);
        })
    }

    UIPointToWorld(wp: cc.Vec2) {
        let np = this.cam.getScreenToWorldPoint(wp);
        return np;
    }
    worldPointToUI(ip: cc.Vec2, worldNode: cc.Node) {
        let wp = worldNode.convertToWorldSpaceAR(ip);
        let cam = cc.Camera.findCamera(worldNode);
        let wp3 = cc.v2(cam.getWorldToScreenPoint(wp));
        return Utils.game.node.convertToNodeSpaceAR(wp3);
    }
    protected onDisable(): void {
        Utils.game.uiCamera.enabled = true;
    }
    protected onEnable(): void {
        Utils.game.uiCamera.enabled = false;
    }
};